<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-5-15
 * Time: 下午11:38
 */
namespace ulue\parts\session\handler;


class FileSessionHandler extends NatureSessionHandler
{

    protected $prefix = 'sess_';
    private $savePath;

    public function open( $savePath, $sessionName )
    {
        $this->savePath  = $savePath;

        if (! is_dir( $this->savePath ) )
        {
            $this->makeDir( $this->savePath );
        }

        return  true ;
    }

    static public function isSupported()
    {
        return true;
    }

    public function read( $id )
    {
        return (string) @file_get_contents ( $this->getFile($id) );
    }

    public function write( $id ,  $data )
    {
        return  file_put_contents( $this->getFile($id),  $data ) ===  false  ?  false  :  true ;
    }

    public function destroy( $id )
    {
        $file  =  $this->getFile($id);

        if ( file_exists( $file ) )
        {
            @unlink( $file );
        }

        return  true ;
    }

    public function gc( $maxlifetime )
    {
        foreach ( glob( "$this->savePath/$this->prefix*" ) as  $file )
        {
            if ( (filemtime($file) + $maxlifetime) < time() &&  file_exists( $file ) )
            {
                unlink( $file );
            }
        }

        return  true ;
    }

    public function getFile($id)
    {
        return $this->savePath.'/'.$this->prefix.$id;
    }

    public function makeDir($path)
    {
        return is_dir($path) || ( $this->makeDir(dirname($path)) && @mkdir($path,0775) );
    }

}